package com.lastingwar.mall.product.exception;


import com.lastingwar.common.exception.BizCodeEnume;
import com.lastingwar.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.lastingwar.mall.product.controller")
@RestControllerAdvice(basePackages = "com.lastingwar.mall.product.controller")
public class ExceptionControllerAdvice {

    //介绍异常的类型
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        //错误日志打印的内容
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        //接受返回的异常结果
        BindingResult bindingResult = e.getBindingResult();
        //存放异常的map
        Map<String,String> errorMap = new HashMap<>();
        //数据监测内容比较多，遍历成映射添加进map
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        //返回的json内容
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }
    //接受其他所有错误
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
